package messagepasser;

/**
 * 
 * @author Rishit Shroff(rshroff)
 * @author Huimin Yang(huiminy)
 * @description Contains the definition of the ListenSocket class
 */

import java.net.ServerSocket;
import java.net.Socket;

class ListenSocket extends Thread  {

	int port;						// port to listen to
	MessagePasser msgPasser;		// reference to the message Passer object
	ReceiveSocket handle;			// reference to ReceiveSocket object
	Socket connection;				
	ServerSocket listenSocket;		// Server socket to accept incoming connection requests
	
	
	/**
	 * Parameterized constructor
	 * @param port
	 * @param m
	 */
    ListenSocket ( int port, MessagePasser m)  {
    	super ();
        this.port = port;
        msgPasser = m;
    }


    public void run  ()  {

    	try  {
    			listenSocket = new ServerSocket ( port );
	            //debug
	            System.out.println ( "Server started:\n  listening on port " + port + "\n\n" );
	            
	            // continuous loop to listen to incoming requests and spawn a new thread everytime
	            // to handle the incoming request
	            while ( true )  {
	                Socket connection = listenSocket.accept();
	                ReceiveSocket receiveMessage = new ReceiveSocket (connection, msgPasser);
	                receiveMessage.start ();
	            }

	    }  catch ( Exception e )  {
	        e.printStackTrace ();
	        System.exit ( 1 );
	    }
	} 
}
